<template>
  <div>
    <el-input  v-model.trim="filterText" class="w-50 m-2" :prefix-icon="Search" placeholder="请输入内容" />
    <el-tree
      ref="treeRef"
      class="filter-tree"
      :data="props.treeData"
      :props="defaultProps"
      default-expand-all
      @node-click="nodeClick"
      @append="appendNode"
      :filter-node-method="filterNode"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import { useThrottleFn } from '@vueuse/core'

interface Tree {
  [key: string]: any;
}
const props = defineProps({
  treeData:{
    type:[Array],
    default:[]
  }
})
const emits = defineEmits<{
  (event: 'clickHandler', data: Object): void;
}>()
// input值
const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();

const defaultProps = {
  children: "children",
  label: "label",
};

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

// 当节点被点击的时候触发，四个参数：对应于节点点击的节点对象，TreeNode 的 node 属性, TreeNode和事件对象
const nodeClick = useThrottleFn((curNode:Tree,b)=>{
  let {parent : {data : parentNode}}= b
 emits('clickHandler',{curNode,parentNode} )
},1000)
// 为Tree中的一个节点追加一个子节点	=(data, parentNode) 1. 要追加的子节点的 data 2. 父节点的 data, key 或 node
const appendNode =(data:Tree,addData:Tree)=>{
  console.log(data,addData,444)
  // if (!data.children) {
  //   data.children = []
  // }
  // data.children.push(addData)
  // treeData.value = [...treeData.value]
}


defineExpose({appendNode})
</script>

<style lang="scss" scoped>
::v-deep .is-current, .is-focusable{
  color: #0052D9;
}
.filter-tree{
  cursor: pointer;
}
</style>
